package com.donger.boms.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.donger.boms.entity.ProductBom;
import com.donger.boms.service.ProductBomService;
import com.donger.boms.utils.Res;
import com.donger.boms.utils.Result;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/productBom")
@AllArgsConstructor
public class ProductBomController {

    private final ProductBomService productBomService;

    /**
     * 树形展示
     * @param number
     * @return
     */
    @GetMapping("/tree/{number}")
    public Result<List<ProductBom>> list(@PathVariable("number") String number) {
        List<ProductBom> bomList = productBomService.queryList(number);
        return Res.ok(recursiveBuildTree(bomList, "0"));
    }

    /**
     * 递归建树
     *
     * @param bomList 查询出的部门数据
     * @param number    父节点number
     * @return 递归后的树列表
     */
    private List<ProductBom> recursiveBuildTree(List<ProductBom> bomList, String number) {
        List<ProductBom> childList = bomList.stream().filter(m -> m.getParentNumber().equals(number)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(childList)) {
            return null;
        }
        for (ProductBom bom : childList) {
            bom.setChildren(recursiveBuildTree(bomList, bom.getNumber()));
        }
        return childList;
    }
}
